package com.zqxq.lottery.api.controller;


import com.zqxq.common.constant.Result;
import com.zqxq.common.enums.CodeEnum;
import com.zqxq.common.utils.DispatcherUtils;
import com.zqxq.common.utils.StrUtils;
import com.zqxq.lottery.api.feign.LotteryServerFeignClient;
import com.zqxq.lottery.entity.bo.jczq.JczqWorldCupBO;
import com.zqxq.lottery.entity.bo.user.UserCashBO;
import com.zqxq.lottery.entity.vo.jczq.JczqMatchVO;
import com.zqxq.lottery.entity.vo.jczq.JczqWorldCupVO;
import com.zqxq.lottery.entity.vo.order.UserOrderBetVO;
import com.zqxq.lottery.entity.vo.order.UserOrderVO;
import com.zqxq.lottery.entity.vo.user.UserCashVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 说    明：   资金管理
 * 创 建 人：	一刀·胡
 * 创建时间：	2018/3/22 17:56
 * 修 改 人：
 * 修改日期：
 **/
@Api(value = "资金流水接口",tags = "资金流水接口")
@Slf4j
@RestController
@RequestMapping(value="/cash",produces = "application/json")
public class CashController {

    @Autowired
    private LotteryServerFeignClient lotteryServerFeignClient;

    /**
     *
     * @param userId
     * @param money
     * @param payWay 支付方式 0-系统；1-支付宝；2-银行卡；3-奖金；4-余额；5-红包；6-微信；99-其它
     * @param payAccount
     * @return
     */
    @PostMapping("/drawCash")
    @ApiOperation(value = "用户提现", notes = "用户提现")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户Id", required = true, paramType = "query",dataType = "Long"),
            @ApiImplicitParam(name = "money", value = "提现金额", required = true, paramType = "query", dataType = "double", defaultValue = "0.00"),
            @ApiImplicitParam(name = "payWay", value = "支付方式 0-系统；1-支付宝；2-银行卡；3-奖金；4-余额；5-红包；6-微信；99-其它", paramType = "query", dataType = "Integer", defaultValue = "1"),
            @ApiImplicitParam(name = "payAccount", value = "账号", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "payPassword", value = "支付密码", required = true, paramType = "query", dataType = "String")
    })
    public Result drawCash(Long userId, BigDecimal money, Integer payWay, String payAccount, String payPassword){
        Result rs = new Result();
        try{
            if(userId == null || money == null || payWay == null || StrUtils.isEmpty(payPassword)){
                rs.setCode(CodeEnum.FAIL_100002.getCode());
                rs.setMsg(CodeEnum.FAIL_100002.getMsg());
            } else {
                //判断金额大于等于10000，走审核流程， 小于1000直接通过支付宝转账
                //查询支付宝账号
                rs = lotteryServerFeignClient.drawCash(userId, money,  payWay, payAccount, payPassword);
            }
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL.getCode());
            rs.setMsg(CodeEnum.FAIL.getMsg());
            log.error("UserCash Page  Error:",e);
        }
        return rs;
    }

    /**
     *  余额消费
     * @param money
     * @param orderId
     * @return
     */
    @PostMapping("/balanceConsume")
    @ApiOperation(value = "余额消费", notes = "余额消费，code=10006  请设置支付密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "money", value = "余额抵扣金额", required = true, paramType = "query", dataType = "double"),
            @ApiImplicitParam(name = "orderId", value = "订单ID", required = true, paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "payPassword", value = "支付密码", required = true, paramType = "query", dataType = "double"),
            @ApiImplicitParam(name = "couponId", value = "优惠券id", required = false,dataType = "Long")
    })
    public Result balanceConsume(BigDecimal money, Long orderId, String payPassword,Long couponId){
        //还需支付金额为0时，直接调用余额支付
        Result rs = new Result();
        try{
            if(money == null || money.compareTo(BigDecimal.ZERO)==0 || orderId == null){
                rs.setCode(CodeEnum.FAIL_100002.getCode());
                rs.setMsg(CodeEnum.FAIL_100002.getMsg());
            } else {
                Result<UserOrderVO> order = lotteryServerFeignClient.getUserOrderH5(orderId);
                UserOrderVO orderVO = order.getData();
                Long lotteryId = DispatcherUtils.parseLong(orderVO.getLotteryId());
                if(lotteryId==21L){
                    //如果是足彩，进行开赛时间的验证
                    List<UserOrderBetVO> UserOrderBetList =  orderVO.getOrderBetList();
                    for (UserOrderBetVO userOrderBetVO : UserOrderBetList){
                        Result<JczqMatchVO> resultJczqMatch = lotteryServerFeignClient.getJczqMatchById(userOrderBetVO.getPeriod());
                        JczqMatchVO jczqMatchVO = resultJczqMatch.getData();
                        Long closeTime = Long.valueOf(jczqMatchVO.getCloseTime());
                        Long currentTime = System.currentTimeMillis();
                        if(closeTime<currentTime){
                            lotteryServerFeignClient.updateUserOrderStatus(String.valueOf(orderId),String.valueOf(7));
                            return new Result(CodeEnum.FAIL_100002.getCode(), "比赛已经开始，不能购买！");
                        }
                    }
                }
                if(lotteryId==210L){
                    List<UserOrderBetVO> orderBetList =  orderVO.getOrderBetList();
                    UserOrderBetVO betVO = orderBetList.get(0);
                    String[] betNums = betVO.getRedNum().split(",");
                    JczqWorldCupBO search = new JczqWorldCupBO();
                    search.setStatus(0);
                    search.setPeriod(orderVO.getPeriod());
                    search.setType(Integer.parseInt(orderBetList.get(0).getPlayType()));
                    Result<Map<String,JczqWorldCupVO>> cupRs = lotteryServerFeignClient.queryWorldCupMap(search);
                    Map<String,JczqWorldCupVO> map = cupRs.getData();
                    for(String betNum : betNums){
                        String key = betVO.getPeriod()+"_"+betVO.getPlayType()+"_"+betNum;
                        JczqWorldCupVO cup = map.get(key);
                        if(null == cup)
                            return new Result(CodeEnum.FAIL_100002.getCode(),"场次已关闭,不能再付款！");
                    }
                }
                rs = lotteryServerFeignClient.balanceConsume(Long.valueOf(orderVO.getUserId()), money, orderId, payPassword,couponId);
                if(rs.getCode()==0 && !ObjectUtils.isEmpty(couponId)){
                    //支付成功后修改优惠券为已使用
                    lotteryServerFeignClient.updateCouponUsed(Long.valueOf(orderVO.getUserId()),couponId);
                }
            }
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL_100005.getCode());
            rs.setMsg(CodeEnum.FAIL_100005.getMsg());
            log.error("UserCash Page  Error:",e);
        }
        return rs;
    }

    @PostMapping("/pageJY")
    @ApiOperation(value = "交易记录", notes = "交易记录")
    public Result<UserCashVO> queryUserCashPageJY(UserCashBO search){
        if(StrUtils.isEmpty(search.getUserId())){
            return  new Result(CodeEnum.FAIL_100002.getCode(),CodeEnum.FAIL_100002.getMsg());
        }
        search.setTypeList(Arrays.asList("1","2","4","5","6","7","8","9","12"));
        return lotteryServerFeignClient.queryUserCashPage(search);
    }

    @PostMapping("/pageZJ")
    @ApiOperation(value = "中奖记录", notes = "中奖记录")
    public Result<UserCashVO> queryUserCashPageZJ(UserCashBO search){
        if(StrUtils.isEmpty(search.getUserId())){
            return  new Result(CodeEnum.FAIL_100002.getCode(),CodeEnum.FAIL_100002.getMsg());
        }
        search.setTypeList(Arrays.asList("3"));
        return lotteryServerFeignClient.queryUserCashPage(search);
    }

    @PostMapping("/pageZS")
    @ApiOperation(value = "钻石交易记录", notes = "钻石交易记录")
    public Result<UserCashVO> queryUserCashPageZS(UserCashBO search){
        if(StrUtils.isEmpty(search.getUserId())){
            return  new Result(CodeEnum.FAIL_100002.getCode(),CodeEnum.FAIL_100002.getMsg());
        }
        search.setPayWay("8");
        search.setTypeList(Arrays.asList("10","11","5","7"));
        return lotteryServerFeignClient.queryUserCashPage(search);
    }

}
